const dbm = require('../config/dbModels');
const db = require('../config/dbIns');
const { aseDecode}=require('../core/crypto')
const { createJWT,decodeJWTId } = require('../core/jwt')
const { createCookie } = require('../core/do-cookie');

class InsertStkNotesDao {
    /**
     *  创建笔记
     * @param ctx 浏览器发送的数据
     */
    static async insert(ctx) {
      let data = ctx.request.body
      
      var { tagValue } = data
      //插入涨跌因素
      if (tagValue) { 
        tagValue.split(',').forEach(async (v, k) => { 
          //删除标签里的前中后的空格
          v = v.replace(/\s/ig, '')
          var [err, res] = await db.findOrCreate(['name'], 'tagList', { name: v })
          if (err) {
            throw new global.errs.ParameterException('涨跌因素标签错误')
          }
        })
      }
      delete data.tagValue
      //插入其他内容
      let [err,dbRes]= await db.insert({ ...data,userId:decodeJWTId(ctx),createdAt:Date.now() },'posts')
      if (err) { 
        throw new global.errs.ParameterException(err)
      }
      //文章被写入到数据库后,得到postId,把对应关系填写到rel_tagList_post表
      if (tagValue) { 
        tagValue.split(',').forEach(async (v) => { 
          var [err,res] = await db.selectOne(['name', 'id'], 'tagList', { name: v })
          db.insert({postId:parseInt(dbRes.insertId),tagId:parseInt(res.id),tagCnName:res.name},'rel_tagList_post')
        })
      }
      return dbRes
    }
  
    static async update(ctx) {
      let data=ctx.request.body
      let [err, dbRes] = await db.update({ stk_name: 's33ad' ,stk_code:9287}, 'posts', {market_region:1118})
      // if(err){
      //   throw new global.errs.ParameterException('用户名或密码错误.')
      // }
      if (err) { 
        throw new global.errs.ParameterException(err)
      }
      return dbRes
    }
}
module.exports = InsertStkNotesDao
